import React, { useState, useEffect } from 'react';
import { Card } from '../../components/Card';
import '../sections/ContentSection.css';

const LONGEVITY_CONTENT = window.LONGEVITY_CONTENT || [];

export const FavoritesSection = () => {
  const [userContent, setUserContent] = useState([]);
  const [favorites, setFavorites] = useState([]);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    chrome.storage.local.get(['userContent', 'favorites'], (result) => {
      setUserContent(result.userContent || []);
      setFavorites(result.favorites || []);
    });
  };

  const allContent = [...LONGEVITY_CONTENT, ...userContent];
  const favoriteItems = allContent.filter(item => favorites.includes(item.id));

  return (
    <section className="favorites-section">
      <div className="section-header">
        <h2>Favorites</h2>
      </div>

      {favoriteItems.length === 0 ? (
        <div className="empty-state">
          <p>No favorites yet. Star items to add them here!</p>
        </div>
      ) : (
        <div className="content-grid">
          {favoriteItems.map((item) => {
            const link = item.link || (item.references && item.references[0]?.url) || '#';
            
            return (
              <Card
                key={item.id}
                className="content-card"
                onClick={() => link !== '#' && chrome.tabs.create({ url: link })}
              >
                <h3>
                  {item.title}
                  <button
                    className="favorite-btn active"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleRemoveFavorite(item.id);
                    }}
                  >
                    ⭐
                  </button>
                </h3>
                <span className="category">{item.category || 'General'}</span>
                <p>{item.description || ''}</p>
              </Card>
            );
          })}
        </div>
      )}
    </section>
  );

  async function handleRemoveFavorite(id) {
    const newFavorites = favorites.filter(f => f !== id);
    await chrome.storage.local.set({ favorites: newFavorites });
    setFavorites(newFavorites);
  }
};

